package org.jeecg.modules.hotel.requisition.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.BusMessageDTO;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.dto.message.TemplateDTO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SysAnnmentTypeEnum;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.apartment.entity.LwgyBaseApartment;
import org.jeecg.modules.basic.demo.bed.entity.LwgyBaseBed;
import org.jeecg.modules.basic.demo.bed.mapper.LwgyBaseBedMapper;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.jeecg.modules.hotel.arrangement.entity.ImportStuHotel;
import org.jeecg.modules.hotel.arrangement.entity.LwgyHotelArrangement;
import org.jeecg.modules.hotel.requisition.entity.BuildDTO;
import org.jeecg.modules.hotel.requisition.entity.LwgyHotelHoliday;
import org.jeecg.modules.hotel.requisition.entity.LwgyHotelRequisition;
import org.jeecg.modules.hotel.requisition.entity.StudentRequest;
import org.jeecg.modules.hotel.requisition.mapper.LwgyHotelRequisitionMapper;
import org.jeecg.modules.hotel.requisition.service.ILwgyHotelRequisitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 调退宿申请
 * @Author: jeecg-boot
 * @Date:   2021-05-04
 * @Version: V1.0
 */



@Service
public class LwgyHotelRequisitionServiceImpl extends ServiceImpl<LwgyHotelRequisitionMapper, LwgyHotelRequisition> implements ILwgyHotelRequisitionService {

    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private ILwgyBaseStudentService iLwgyBaseStudentService;
    @Autowired
    private ILwgyBaseBedService iLwgyBaseBedService;
    @Autowired
    private LwgyBaseBedMapper lwgyBaseBedMapper;
    @Autowired
    private LwgyHotelRequisitionMapper lwgyHotelRequisitionMapper;
    @Autowired
    private ILwgyHotelRequisitionService ILwgyHotelRequisitionService;



    public void pushMsg(LwgyHotelRequisition lwgyHotelRequisition, String username, List<String> roles, LwgyBaseStudent lwgyBaseStudent) {
        String studentTeacher = lwgyBaseStudent.getStudentTeacher();
        String teacherName = "";
        if(roles.contains("user_students")){//学生发起的申请
            if(oConvertUtils.isNotEmpty(studentTeacher)){
                String[] fields = studentTeacher.split(",");
                teacherName = sysBaseAPI.getUserById(fields[0]).getUsername();
                lwgyHotelRequisition.setAuditProcess("3");
                //推送给辅导员
                sysBaseAPI.sendBusAnnouncement(new BusMessageDTO(username,teacherName,"事务申请",lwgyHotelRequisition.getReason(),"1", SysAnnmentTypeEnum.CHANGE.getType(),""));
            }else{//没有查询到学生的辅导员，推送给管理员
                teacherName = "admin";
                //到管理员流程
                lwgyHotelRequisition.setAuditProcess("2");
                sysBaseAPI.sendBusAnnouncement(new BusMessageDTO(username,teacherName,"事务申请",lwgyHotelRequisition.getReason(),"1", SysAnnmentTypeEnum.CHANGE.getType(),""));
            }
        }else if(roles.contains("fdy")){//辅导员发起的调宿申请
            teacherName = "admin";
            lwgyHotelRequisition.setAuditProcess("2");
            sysBaseAPI.sendBusAnnouncement(new BusMessageDTO(username,teacherName,"事务申请",lwgyHotelRequisition.getReason(),"1", SysAnnmentTypeEnum.CHANGE.getType(),""));
        }
        lwgyHotelRequisition.setFromUser(username);
        lwgyHotelRequisition.setToUser(teacherName);
    }


//    @Override
//    public IPage<LwgyHotelRequisition> queryPageCustomers(Page<LwgyHotelRequisition> page, QueryWrapper<LwgyHotelRequisition> queryWrapper) {
//        queryWrapper.isNotNull("stu.id");
//        return page.setRecords(lwgyHotelRequisitionMapper.queryPageListCustoms(page,queryWrapper));
//    }

    @Override
    public IPage<LwgyHotelRequisition> queryPageListCustoms(Page<LwgyHotelRequisition> page, QueryWrapper<LwgyHotelRequisition> queryWrapper) {
       queryWrapper.isNotNull("stu.id");
       return page.setRecords(lwgyHotelRequisitionMapper.queryPageListCustoms(page,queryWrapper));
   }

    @Override
    public List<StudentRequest> getStudentRequisition(LwgyBaseApartment lwgyBaseApartment) {
        return lwgyHotelRequisitionMapper.getStudentRequisition(lwgyBaseApartment);

    }
    @Override
    public IPage<LwgyHotelRequisition> buildingQuery(Page<LwgyHotelRequisition> page, QueryWrapper<LwgyHotelRequisition> queryWrapper) {
        return page.setRecords(lwgyHotelRequisitionMapper.buildingQuery(page,queryWrapper));
    }

    @Override
    public List<BuildDTO> getbuild() {
        return lwgyHotelRequisitionMapper.getbuild();
    }

    @Override
    public List<Map<String,String>> listByPids(String pid){
        return lwgyHotelRequisitionMapper.listByPids(pid);
    }
    @Override
    public List<Map<String,String>> listByPides(String pid){
        return lwgyHotelRequisitionMapper.listByPides(pid);
    }
    @Override
    public List<Map<String,String>> listByStuNum(String studentNumber){
        return lwgyHotelRequisitionMapper.listByStuNum(studentNumber);
    }
//    @Override
//    public List<Map<String, String>> listByPids(String pid) {
//        return ILwgyHotelRequisitionService.listByPids(pid);
//    }

    public void pushChangeMsg(LwgyHotelArrangement lwgyHotelArrangement, String username, String type) {
        String oldcwh= "";
        String newcwh= "";
        String student_number= "";
        String student_sex= "";
        String student_xy= "";
        String student_name= "";
        String student_year= "";

        String code="bpm_xy_change";
        List<Map<String,String>> list = iLwgyBaseStudentService.getStuInfoById(lwgyHotelArrangement.getStudentId());
        System.out.println("list:"+list);
        if(list.size()>0) {
            Map map = list.get(0);
            student_number = (map.get("student_number")==null || map.get("student_number").equals(""))?"无学号信息":map.get("student_number").toString();
            student_sex =(map.get("student_sex")==null || map.get("student_sex").equals(""))?"无性别信息":map.get("student_sex").toString();
            student_xy =(map.get("student_college")==null || map.get("student_college").equals(""))?"无学院信息":map.get("student_college").toString();
            student_name =(map.get("student_name")==null || map.get("student_name").equals(""))?"无姓名信息":map.get("student_name").toString();
            student_year =(map.get("student_year")==null || map.get("student_year").equals(""))?"无年级信息":map.get("student_year").toString();

        }

        if(oConvertUtils.isNotEmpty(lwgyHotelArrangement.getBeforeBed())){
            LwgyBaseBed lwgyBaseBed = lwgyBaseBedMapper.queryBedById(lwgyHotelArrangement.getBeforeBed());
            oldcwh=lwgyBaseBed.getCampusName()+lwgyBaseBed.getBuildingName()+lwgyBaseBed.getRoomName();
        }else{
            oldcwh = "无";
        }
        if(oConvertUtils.isNotEmpty(lwgyHotelArrangement.getAfterBed())){
            LwgyBaseBed lwgyBaseBed = lwgyBaseBedMapper.queryBedById(lwgyHotelArrangement.getAfterBed());
            newcwh=lwgyBaseBed.getCampusName()+lwgyBaseBed.getBuildingName()+lwgyBaseBed.getRoomName();

        }else{
            newcwh = "无";
        }

        Map<String, String> map = new HashMap<>();
        map.put("xy", student_year+"级"+student_xy+"的学生："+student_name+":"+student_number+"("+student_sex+")");
        map.put("fdyname", username);
        map.put("type", type);
        map.put("oldcwh",oldcwh);
        map.put("newcwh",newcwh);
        String content  = sysBaseAPI.parseTemplateByCode(new TemplateDTO(code,map));
        System.out.println("content:"+content);
        sysBaseAPI.sendSysAnnouncement(new MessageDTO( username, "admin","辅导员调整宿舍", content, "1"));


    }



    public void pushWx(LwgyHotelRequisition lwgyHotelRequisition, String username, List<String> roles, LwgyBaseStudent lwgyBaseStudent) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

        String[] keys = new String[]{lwgyHotelRequisition.getBehavioral(),"辅导员："+lwgyHotelRequisition.getFromUser(),df.format(new Date())};
        String user=lwgyHotelRequisition.getStudentName()+"-"+lwgyHotelRequisition.getStudentCampus();
        sysBaseAPI.sendCheckByWeiXin(keys,user);

    }

    @Override
    public IPage<LwgyHotelRequisition> queryHolidayPageList(Page<LwgyHotelRequisition> page, QueryWrapper<LwgyHotelRequisition> queryWrapper) {

        List<LwgyHotelRequisition> list1 = lwgyHotelRequisitionMapper.queryHolidayPageList(page,queryWrapper);// 查询所有的申请事务申请假期的学生
        if(list1 != null && !list1.isEmpty()){
            Map<String, LwgyHotelRequisition> map = new HashMap<>(list1.size());
            for (LwgyHotelRequisition holiday : list1) {
                map.put(holiday.getStudentId(), holiday);
            }

            List<LwgyHotelRequisition> list2 = lwgyHotelRequisitionMapper.selectHolidayStuList(list1);// 查询学生的床位
            for (LwgyHotelRequisition hotel : list2) {
                LwgyHotelRequisition holiday = map.get(hotel.getHolidayStudentId());
                if (holiday != null) {
                    holiday.setBuildingId(hotel.getBuildingId());
                    holiday.setRoomId(hotel.getRoomId());
                }
            }
        }

        return page.setRecords(list1);
    }

    @Override
    public LwgyHotelRequisition getStuAdmin(String studentId){
        return lwgyHotelRequisitionMapper.getStuAdmin(studentId);
    }

    @Override
    public List<LwgyHotelHoliday> outHolidayStu(LwgyHotelRequisition requisition) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roles = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
        if(roles.contains("fdy")){
            List<String> classId = iLwgyBaseStudentService.getClassIdBySysUser(sysUser);
            if (oConvertUtils.listIsNotEmpty(classId)) {
                StringBuilder sb = new StringBuilder();
                for (String id : classId) {
                    sb.append(id).append(",");
                }
                // 去掉最后一个逗号
                sb.deleteCharAt(sb.length() - 1);
                requisition.setStudentClass(sb.toString());
            } else {
                requisition.setStudentClass(null);
            }
        }
        List<LwgyHotelHoliday> holidayList = lwgyHotelRequisitionMapper.outHolidayStu(requisition);

        if (holidayList != null && !holidayList.isEmpty()) {
            List<LwgyHotelHoliday> holidayRoomList = lwgyHotelRequisitionMapper.queryStudentRoomId(holidayList);// 查询假期床位
            List<LwgyHotelHoliday> oldRoomList = lwgyHotelRequisitionMapper.queryStudentRoomIdOld(holidayList);// 查询原床位

            Map<String, LwgyHotelHoliday> holidayRoomMap = new HashMap<>(holidayRoomList.size());
            for (LwgyHotelHoliday holidayRoom : holidayRoomList) {
                holidayRoomMap.put(holidayRoom.getHolidayStudentId(), holidayRoom);
            }

            Map<String, LwgyHotelHoliday> oldRoomMap = new HashMap<>(oldRoomList.size());
            for (LwgyHotelHoliday oldRoom : oldRoomList) {
                oldRoomMap.put(oldRoom.getStudentId(), oldRoom);
            }

            for (LwgyHotelHoliday holiday : holidayList) {
                LwgyHotelHoliday holidayRoom = holidayRoomMap.get(holiday.getStudentId());
                if (holidayRoom != null) {
                    holiday.setBuildingId(holidayRoom.getBuildingId());
                }
                LwgyHotelHoliday oldRoom = oldRoomMap.get(holiday.getStudentId());
                if (oldRoom != null) {
                    holiday.setOldBuildId(oldRoom.getBuildingId());
                    holiday.setOldRoomId(oldRoom.getRoomId());
                }
            }
        }
        return holidayList;
    }

    @Override
    public void batchDelete(String ids) {
        List<String> strings = Arrays.asList(ids.split(","));
        List<LwgyHotelHoliday> list = new ArrayList<>();
        for (String string : strings) {
            LwgyHotelHoliday lwgyHotelHoliday = new LwgyHotelHoliday();
            lwgyHotelHoliday.setId(string);
            lwgyHotelHoliday.setDelFlag("1");
            list.add(lwgyHotelHoliday);
        }
        if (!list.isEmpty()) {
            lwgyHotelRequisitionMapper.updateBatchByHolidayId(list);
        }
    }
}
